#encoding=utf8
from flask import Flask
import json
from flask import request
import urllib2
app = Flask(__name__)


@app.route('/relay',methods=['POST'])
def dingtalk_relay():
    access_token = request.args.get("access_token")
    url = "https://oapi.dingtalk.com/robot/send?access_token=" + access_token
    newReq = {}
    newReq['msgtype'] = 'text'
    newReq['text'] = {}
    print request.json
    jdata = request.json
    content = u"镜像名:\t" + jdata['repository']['name'] +  \
        u'\n最新版本号(Tag):\t' + jdata['push_data']['tag'] + \
        u"\n最新镜像URL:\tregistry." + jdata['repository']['region'] + ".aliyuncs.com/" + jdata['repository']['repo_full_name']+ ":" + jdata['push_data']['tag']  + \
        u'\n最新镜像生成时间:\t' + jdata['push_data']['pushed_at'] + \
        u"\nDigest:\t" + jdata['push_data']['digest']
    newReq['text']['content'] =  content
    data = json.dumps(newReq)
    req = urllib2.Request(url, data, {'Content-Type':'application/json'})
    result = urllib2.urlopen(req)
    res = result.read()
    return res


if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0',port = 8880)